import axios from "axios";
import {getUserInfo, clearUserInfo} from "./common.js";
import router from "@/router/index.js";
import {ElMessage} from "element-plus";

axios.defaults.baseURL = process.env.VUE_APP_BASE_API
axios.interceptors.request.use(
    config => {
        const token = getUserInfo().token
        if (token && token !== 'undefined') {
            config.headers['Authorization'] = 'Bearer ' + token
        } else {
            if (config.url !== '/login') {
                clearUserInfo()
                router.push('Login')
            }
        }
        return config
    },
)

axios.interceptors.response.use(
    res => {
        if (res.data.status === 'error' || parseInt(res.data.code) !== 200) {
            ElMessage({
                type: 'error',
                message: (res.data.content && res.data.content.msg) ? res.data.content.msg : res.data.msg
            })
            if (parseInt(res.data.code) === 401) {
                clearUserInfo()
                router.push('Login')
            }
        }
        return res
    },
    error => {
        if (parseInt(error.response.status) === 500) {
            ElMessage({
                type: 'error',
                message: error.response.data.message
            })
        }
    }
)

const post = (url, formData) => {
    return new Promise((resolve, reject) => {
        axios.post(url, formData).then(res => {
            if (res.data.status === 'success') resolve(res.data.content)
            else reject(res.data.content.msg)
        })
    })
}

export default post